import re
import pandas as pd
import sys

def parse_txt_to_csv(input_file, output_file):
    # 读取txt文件内容
    with open(input_file, 'r', encoding='utf-8') as file:
        content = file.read()
    
    # 使用正则表达式匹配每个题目的完整块
    pattern = r'题目：(.*?)\nA\. (.*?)\nB\. (.*?)\nC\. (.*?)\nD\. (.*?)\n.*?Predicted: (.*?)Ground Truth: ([A-D])'
    matches = re.findall(pattern, content, re.DOTALL)
    
    # 提取数据
    data = []
    for match in matches:
        question = match[0].strip()
        option_a = f"A. {match[1].strip()}"
        option_b = f"B. {match[2].strip()}"
        option_c = f"C. {match[3].strip()}"
        option_d = f"D. {match[4].strip()}"
        response = match[5].strip()
        ground_truth = match[6].strip()
        
        data.append([question, option_a, option_b, option_c, option_d, response, ground_truth])
    
    # 创建DataFrame
    df = pd.DataFrame(data, columns=['题目', '选项A', '选项B', '选项C', '选项D', 'Response', 'Ground Truth'])
    
    # 保存为CSV文件
    df.to_csv(output_file, index=False, encoding='utf-8-sig')
    print(f"成功解析 {len(data)} 条题目，已保存到 {output_file}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("用法: python script.py input.txt output.csv")
        print("示例: python script.py questions.txt output.csv")
    else:
        input_file = sys.argv[1]
        output_file = sys.argv[2]
        parse_txt_to_csv(input_file, output_file)